<?php

namespace App\Http\Controllers\api;

use App\Game;
use Carbon\Carbon;

use Illuminate\Support\Facades\Cache;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller
{

    // 获取用户参与的互动
    public function join_games(){

        // 获取登录用户实例对象
        $user = \Auth::guard("api")->user();
        $games = $user->games;
        return $games;

    }


    // 获取用户创建的活动
    public function create_games(){

        $user = \Auth::guard("api")->user();

        $games = Game::where("user_id",$user->id)->orderBy("created_at","desc")->get();

        foreach ($games as $k=>$game){
            $games[$k]["type_name"] = $game->type->name;
        }

        return $games;

    }


    // 保存用户头像
    public function save_icon(Request $request){


        // 图片的保存路径
        $path = base_path("public/upload/");

        // 获取上传文件实例对象
        $file = $request->file('icon');

        //3 上传图片方法
        $ext = $file->getClientOriginalExtension();  //扩展名 girl_0.jpg
        $file_name = time() . "." . $ext;           //重命名上传文件 12345.jpg

        $file->move($path, $file_name); //移动至指定目录


        // 4 保存icon名称到数据库表
        $user = \Auth::guard('api')->user();

        $user->icon = $file_name;

        $res = $user->save();

        return response()->json(["res"=>$res,"user"=>$user]);


    }


    // 用户登录
    public function login(Request $request){

        //return $request;

        $bool = \Auth("web")->attempt($request->only("email","password"));
        //$bool = true;

        if($bool){

            //1 更新数据库表中的token

            $api_token = session_create_id();
            $user = User::where("email",$request->email)->get()[0];
            $user-> api_token = $api_token;
            $res = $user->save();


            // 2 把token保存到缓存

            $expiresAt = Carbon::now()->addMinutes(120);// 有效期2个小时
            Cache::put($api_token,$user,$expiresAt);  // 设置缓存内token有效期


            return response()->json(["code"=>200,"msg"=>"登录成功","user"=>$user]);


        }else{

            return response()->json(["code"=>3000,"msg"=>"用户名或密码有误"]);

        }


        // 1 颁发新令牌,保存到数据库表

        // 2 更新缓存中的token(2个小时有效期)



    }


    //用户注册
    public function reg(Request $request){

        return User::create([
            'name' => $request->name,
            'email' => $request->email,
            'tel' => $request->tel,
            'password' => bcrypt($request->password),
            "api_token" => session_create_id()
        ]);


    }

    // 测试路由
    public function test(){

        $arr = ["token"=>"123","name"=>"tom"];

        $expiresAt = Carbon::now()->addSeconds(30);

        Cache::put('name', $arr, $expiresAt);  //

        $cache_val = Cache::get("name");

        dd($cache_val);

    }



}
